from typing import Annotated
from fastapi import Depends
from sqlmodel import SQLModel, Session, create_engine

_sqlite_file_name = "database.db"
_sqlite_url = f"sqlite:///{_sqlite_file_name}"

# "check_same_thread": False可以让FastAPI在不同线程中使用同一个SQLite数据库（FastAPI单个请求可能使用多个线程）
_connect_args = {"check_same_thread": False}
_engine = create_engine(_sqlite_url, connect_args=_connect_args)

def create_db_and_tables():
    SQLModel.metadata.create_all(_engine)

def new_session():
    return Session(_engine)

def get_session():
    with Session(_engine) as session:
        yield session
        
SessionDep = Annotated[Session, Depends(get_session)]